- Suanlab Matplotlib 강의: [YouTube]]
knitr::opts_chunk$set(error = TRUE)
options(reticulate.repl.quiet =TRUE)
library(reticulate)
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
plt.style.use(['seaborn-notebook']) #seaborn style 가져오기
파이썬의 대표적인 과학 계산용 그래프 라이브러리
선 그래프, 히스토그램, 산점도 등의 고품질 그래프 제공
저수준 api를 사용한 다양한 시각화 기능 제공
다양한 운영체제와 그래픽 백엔드에서 동작
plt.Figure: 축과 그래픽, 텍스트, 레이블을 표시하는 모든 객체를 포함하는 컨테이너plt.Axes: 눈금과 레이블이 있는 테두리 박스로 시각화를 형성하는 플롯 요소 포함fig = plt.figure()
ax = plt.axes()
plt.plot([0, 0.2, 0.4, 0.6,0.8,1] * 5);
plt.show();plt.clf()# clf는 reset plot surface
x = np.arange(0, 10, 0.01)
fig = plt.figure()
plt.plot(x, np.sin(x));plt.show();plt.clf()
plt.plot(x, np.sin(x));
plt.plot(x, np.cos(x));plt.show();plt.clf()
plt.plot(np.random.randn(50).cumsum());plt.show();plt.clf()
| 문자 | 스타일 |
|---|---|
- |
‘solid’ |
-- |
‘dashed’ |
-. |
‘dashdot’ |
: |
‘dotted’ |
plt.plot(np.random.randn(50).cumsum(), linestyle='solid');
plt.plot(np.random.randn(50).cumsum(), linestyle='dashed');
plt.plot(np.random.randn(50).cumsum(), linestyle='dashdot');
plt.plot(np.random.randn(50).cumsum(), linestyle='dotted');
plt.show();plt.clf()
plt.plot(np.random.randn(50).cumsum(), linestyle='-');
plt.plot(np.random.randn(50).cumsum(), linestyle='--');
plt.plot(np.random.randn(50).cumsum(), linestyle='-.');
plt.plot(np.random.randn(50).cumsum(), linestyle=':');
plt.show();plt.clf()
| 문자 | 색상 |
|---|---|
b |
‘blue’ |
g |
‘green’ |
r |
‘red’ |
m |
‘cyan’ |
y |
‘magenta’ |
k |
‘black’ |
w |
‘white’ |
plt.plot(np.random.randn(50).cumsum(), linestyle='-', color='g');
plt.plot(np.random.randn(50).cumsum(), linestyle='--', color='#1243FF');
plt.plot(np.random.randn(50).cumsum(), linestyle='-.', color=(0.2, 0.4, 0.6));
plt.plot(np.random.randn(50).cumsum(), linestyle=':', color='darkblue');
plt.show();plt.clf()
plt.plot(np.random.randn(50).cumsum(), linestyle='-', color='skyblue');
plt.plot(np.random.randn(50).cumsum(), linestyle='--', color='dodgerblue');
plt.plot(np.random.randn(50).cumsum(), linestyle='-.', color='royalblue');
plt.plot(np.random.randn(50).cumsum(), linestyle=':', color='navy');
plt.show();plt.clf()
plt.plot(np.random.randn(50).cumsum(), 'b-');
plt.plot(np.random.randn(50).cumsum(), 'r--');
plt.plot(np.random.randn(50).cumsum(), 'c-.');
plt.plot(np.random.randn(50).cumsum(), 'm:');
plt.show();plt.clf()
#color 색깔까지 한번에 지정가능
plt.plot(np.random.randn(50));
plt.xlim(-1, 50);
plt.ylim(-5, 5);
plt.show();plt.clf()
plt.plot(np.random.randn(50));
plt.axis([-1,50,-5,5]);
plt.show();plt.clf()
plt.plot(np.random.randn(50));
plt.axis('tight');
plt.show();plt.clf()
plt.plot(np.random.randn(50));
plt.axis('equal');
plt.show();plt.clf()
plt.plot(np.random.randn(50));
plt.title("title");
plt.xlabel("x");
plt.ylabel("random.randn");
plt.show();plt.clf()
plt.plot(np.random.randn(50), label='A');
plt.plot(np.random.randn(50), label='B');
plt.plot(np.random.randn(50), label='C');
plt.title("title");
plt.xlabel("x");
plt.ylabel("random.randn");
plt.legend();
plt.show();plt.clf()
set([f.name for f in mpl.font_manager.fontManager.ttflist])
#font list 확인
## {'Copperplate Gothic Bold', 'HYGothic-Extra', 'STIXSizeThreeSym', 'Kunstler Script', 'Ravie', 'OCR A Extended', 'Yu Gothic', 'cmr10', 'Harlow Solid Italic', 'HYMyeongJo-Extra', 'Calisto MT', 'Baskerville Old Face', 'Agency FB', 'NanumSquare', 'HYPost-Medium', 'Goudy Old Style', 'Gill Sans MT', 'Castellar', 'Script MT Bold', 'Berlin Sans FB Demi', 'Gill Sans MT Condensed', 'Ebrima', 'HYGungSo-Bold', 'Marlett', 'Haan Wing2', 'Kristen ITC', 'Pristina', 'MingLiU-ExtB', 'Onyx', 'Microsoft Himalaya', 'DejaVu Serif Display', 'Eras Light ITC', 'Snap ITC', 'Gill Sans MT Ext Condensed Bold', 'HCR Dotum Ext', 'Showcard Gothic', 'Perpetua Titling MT', 'Bookshelf Symbol 7', 'Sitka Small', 'HYSinMyeongJo-Medium', 'Rockwell', 'Imprint MT Shadow', 'MS Gothic', 'Copperplate Gothic Light', 'STIXNonUnicode', 'Tw Cen MT Condensed Extra Bold', 'Bradley Hand ITC', 'Wingdings 2', 'Algerian', 'Rockwell Extra Bold', 'Goudy Stout', 'Rage Italic', 'Tw Cen MT', 'Webdings', 'MS Reference Specialty', 'Candara', 'Lucida Fax', 'Nirmala UI', 'Gill Sans Ultra Bold Condensed', 'Franklin Gothic Medium Cond', 'Forte', 'Consolas', 'Lucida Calligraphy', 'Brush Script MT', 'Harrington', 'Microsoft YaHei', 'Microsoft JhengHei', 'Garamond', 'MV Boli', 'Bauhaus 93', 'Sylfaen', 'Palatino Linotype', 'HYPost-Light', 'Eras Medium ITC', 'Corbel', 'Han Santteut Dotum', 'Segoe MDL2 Assets', 'HYGothic-Medium', 'Constantia', 'Bodoni MT', 'Papyrus', 'Franklin Gothic Heavy', 'MoeumT R', 'Matura MT Script Capitals', 'Freestyle Script', 'HoloLens MDL2 Assets', 'Impact', 'MS Outlook', 'Lucida Console', 'Vivaldi', 'Modern No. 20', 'Javanese Text', 'DejaVu Serif', 'Microsoft Tai Le', 'Cooper Black', 'Wide Latin', 'Calibri', 'Old English Text MT', 'Playbill', 'NewJumja', 'HYGraphic-Medium', 'Elephant', 'Century', 'Niagara Solid', 'HYHeadLine-Medium', 'Arial', 'Microsoft Uighur', 'Centaur', 'Parchment', 'Jokerman', 'Book Antiqua', 'Wingdings 3', 'Footlight MT Light', 'Lucida Sans Unicode', 'HYPMokGak-Bold', 'Magic R', 'STIXSizeFourSym', 'Segoe Script', 'Comic Sans MS', 'STIXGeneral', 'Ink Free', 'Palace Script MT', 'MS Reference Sans Serif', 'Engravers MT', 'Gadugi', 'HCR Dotum', 'Colonna MT', 'Tw Cen MT Condensed', 'Hancom Gothic', 'Batang', 'Ami R', 'Gulim', 'Gill Sans Ultra Bold', 'Leelawadee', 'Times New Roman', 'Lucida Sans', 'Rockwell Condensed', 'Leelawadee UI', 'SimSun', 'Vladimir Script', 'Bernard MT Condensed', 'Curlz MT', 'Franklin Gothic Medium', 'DejaVu Sans Mono', 'Wingdings', 'cmss10', 'Lucida Bright', 'Poor Richard', 'MT Extra', 'cmtt10', 'Maiandra GD', 'Trebuchet MS', 'Arial Rounded MT Bold', 'cmsy10', 'Segoe UI Symbol', 'Tahoma', 'Eras Bold ITC', 'Cambria', 'Myanmar Text', 'Gigi', 'Bookman Old Style', 'Microsoft New Tai Lue', 'Berlin Sans FB', 'cmmi10', 'STIXSizeTwoSym', 'Mistral', 'DejaVu Sans Display', 'Eras Demi ITC', 'Mongolian Baiti', 'Headline R', 'French Script MT', 'DejaVu Sans', 'New Gulim', 'Malgun Gothic', 'HCR Batang Ext', 'HancomEQN', 'Segoe UI Emoji', 'Lucida Handwriting', 'Niagara Engraved', 'Bell MT', 'Perpetua', 'HCR Batang ExtB', 'SimSun-ExtB', 'Microsoft Sans Serif', 'Informal Roman', 'Symbol', 'Microsoft Yi Baiti', 'Century Gothic', 'Century Schoolbook', 'Segoe UI Historic', 'Felix Titling', 'Verdana', 'Haettenschweiler', 'Segoe UI', 'Yet R', 'Dubai', 'Franklin Gothic Demi Cond', 'Britannic Bold', 'HyhwpEQ', 'Viner Hand ITC', 'Chiller', 'Stencil', 'STIXSizeFiveSym', 'Lucida Sans Typewriter', 'Californian FB', 'Blackadder ITC', 'Courier New', 'Segoe Print', 'NanumSquare_ac', 'HCR Batang', 'Gloucester MT Extra Condensed', 'Franklin Gothic Book', 'Pyunji R', 'Bahnschrift', 'cmb10', 'Edwardian Script ITC', 'Broadway', 'Georgia', 'Microsoft PhagsPa', 'Juice ITC', 'High Tower Text', 'Tempus Sans ITC', 'cmex10', 'Monotype Corsiva', 'Magneto', 'Gabriola', 'Franklin Gothic Demi', 'STIXSizeOneSym', 'HYShortSamul-Medium'}
font1 = {'family' : 'DejaVu Sans', 'size':24, 'color': 'black'}
font2 = {'family' : 'Tamil MN', 'size':18,'weight':'bold', 'color': 'darkred'}
font3 = {'family' : 'STIXGeneral', 'size':16, 'weight':'light', 'color': 'blue'}
plt.plot([1,2,3,4,5],[1,2,3,4,5]);
plt.title('title', fontdict=font1);
plt.xlabel('xlabel', fontdict=font2);
plt.ylabel('ylabel', fontdict=font3);
plt.show();plt.clf()
## findfont: Font family ['Tamil MN'] not found. Falling back to DejaVu Sans.
| 숫자 | loc지정 |
|---|---|
0 |
‘best’ |
1 |
‘upper right’ |
2 |
‘upper left’ |
3 |
‘lower left’ |
4 |
‘lower right’ |
5 |
‘right’ |
6 |
‘center left’ |
7 |
‘center right’ |
8 |
‘lower center’ |
9 |
‘upper center’ |
fix, ax = plt.subplots();
ax.plot(np.random.randn(10), '-r', label='A');
ax.plot(np.random.randn(10), ':g', label='B');
ax.plot(np.random.randn(10), '--b', label='C');
ax.axis('equal');
ax.legend();
plt.show();plt.clf()
fix, ax = plt.subplots()
ax.plot(np.random.randn(10), '-r', label='A');
ax.plot(np.random.randn(10), ':g', label='B');
ax.plot(np.random.randn(10), '--b', label='C');
ax.axis('equal');
ax.legend(loc='lower right', frameon=False, ncol=2);
plt.show();plt.clf()
# 범례박스를 없애고 2컬럼으로 범례표시
fix, ax = plt.subplots();
ax.plot(np.random.randn(10), '-r', label='A');
ax.plot(np.random.randn(10), ':g', label='B');
ax.plot(np.random.randn(10), '--b', label='C');
ax.axis('equal');
ax.legend(fancybox=True, framealpha =1, shadow=True, borderpad=1);
plt.show();plt.clf();
# alpha를 주면 범례 배경색이 드러남 그리고 보더패드에 음영넣어서 프레임씌움
plt.figure(figsize=(8,4));
x = np.linspace(0, 10, 1000);
y = np.cos(x[:, np.newaxis] * np.arange(0, 2, 0.2));
lines = plt.plot(x, y);
plt.legend(lines[:3], ['c1', 'c2', 'c3'], loc='upper right');
plt.show();plt.clf();
plt.figure(figsize=(8,4));
x = np.linspace(0, 10, 1000);
y = np.cos(x[:, np.newaxis] * np.arange(0, 2, 0.2));
lines = plt.plot(x, y);
plt.legend(lines[:3], ['c1', 'c2', 'c3']);
plt.plot(x, y[:,0], label = 'c1');
plt.plot(x, y[:,1], label = 'c2');
plt.plot(x, y[:,2], label = 'c3');
plt.plot(x, y[:,3:]);
plt.legend(framealpha =1, frameon=True, loc='upper right');
plt.show();plt.clf()
#alpha를줬기 때문에 범례가 불투명해짐
x = np.linspace(0, 20, 100);
I = np.cos(x) - np.cos(x[:, np.newaxis]);
plt.imshow(I, cmap='RdBu');plt.colorbar();
plt.show();plt.clf()
#colormap을 범례로
speckles = (np.random.random(I.shape) < 0.01);
I[speckles] = np.random.normal(0, 3, np.count_nonzero(speckles));
plt.imshow(I, cmap='RdBu');
plt.colorbar(extend='both');
plt.clim(-1, 1);
plt.show();plt.clf()
# color bar -1, 1범위지정 및 extend 뾰족하게 노이즈 포함하여 그림
speckles = (np.random.random(I.shape) < 0.01);
I[speckles] = np.random.normal(0, 3, np.count_nonzero(speckles));
plt.imshow(I, cmap=plt.cm.get_cmap('Blues', 5));
plt.colorbar();
plt.clim(-1, 1);
plt.show();plt.clf()
# color 숫자를 5개로 지정
ax1 = plt.axes();
ax2 = plt.axes([0.65, 0.5, 0.2, 0.3]);
plt.show();plt.clf()
# 0.65 0.5 위치에 0.2 0.3짜리 다중플롯 생성
for i in range(1, 10):
plt.subplot(3, 3, i);
plt.text(0.5, 0.5, str((3, 3, i)), ha='center')
plt.show().plt.clf()
## Error in py_call_impl(callable, dots$args, dots$keywords): AttributeError: 'NoneType' object has no attribute 'plt'
##
## Detailed traceback:
## File "<string>", line 1, in <module>
fig = plt.figure();
fig.subplots_adjust(hspace=0.4, wspace=0.4)
for i in range(1, 10):
plt.subplot(3, 3, i);
plt.text(0.5, 0.5, str((3, 3, i)), ha='center')
plt.show().plt.clf()
#subplot 여백 주기
## Error in py_call_impl(callable, dots$args, dots$keywords): AttributeError: 'NoneType' object has no attribute 'plt'
##
## Detailed traceback:
## File "<string>", line 1, in <module>
fig, ax = plt.subplots(3, 3, sharex='col', sharey='row');
plt.show()
for i in range(3):
for j in range(3):
ax[i, j].text(0.5, 0.5, str((i, j)), ha='center');
fig
plt.show();plt.clf()
grid =plt.GridSpec(2, 3, wspace=0.4, hspace=0.4)
plt.subplot(grid[0,0]);
plt.subplot(grid[0,1:]);
plt.subplot(grid[1,:2]);
plt.subplot(grid[1,2]);
plt.show();plt.clf()
# grid spec으로 합친것
plt.figure(figsize=(5,6));
x = range(1,21);
columns = [np.random.rand(20) * i for i in range(1,7)];
i = 0
for c in columns:
i += 1
plt.subplot(3,2,i);
plt.plot(x, c, marker='o', linewidth=1, label=c);
plt.xlim(-1,21);
plt.ylim(c.min()-1, c.max()+1)
## <AxesSubplot:>
## [<matplotlib.lines.Line2D object at 0x000000006B4422E0>]
## (-1.0, 21.0)
## (-0.8836675380789164, 1.9804775591622192)
## <AxesSubplot:>
## [<matplotlib.lines.Line2D object at 0x000000006AB96E80>]
## (-1.0, 21.0)
## (-0.9833917965443415, 2.9680184006516956)
## <AxesSubplot:>
## [<matplotlib.lines.Line2D object at 0x000000006B64D910>]
## (-1.0, 21.0)
## (-0.8431946394731905, 3.615564821384121)
## <AxesSubplot:>
## [<matplotlib.lines.Line2D object at 0x000000006569A550>]
## (-1.0, 21.0)
## (-0.41725013267630695, 4.904733162159994)
## <AxesSubplot:>
## [<matplotlib.lines.Line2D object at 0x000000006A04B400>]
## (-1.0, 21.0)
## (-0.831375914545134, 5.756160412727381)
## <AxesSubplot:>
## [<matplotlib.lines.Line2D object at 0x000000006AAC5C10>]
## (-1.0, 21.0)
## (-0.5470891084051226, 6.693758709313335)
plt.show();plt.clf()
#ylim에 여백을 준것 +1 -1
fig, ax = plt.subplots();
ax.axis([0, 10, 0, 10]);
ax.text(3, 6, ". transData(3,6)", transform=ax.transData);
ax.text(0.2, 0.4, ". transAxes(0.2, 0.4", transform=ax.transAxes);
ax.text(0.2, 0.2, ". transFigure(0.2, 0.2)", transform=fig.transFigure);
plt.show()
# transData는 좌표에 정확히 표시
# transAxes 축정보 0~1까지 해서 표시
# transFigure는 전체에서 위치 표시
ax.set_xlim(-6,10);
ax.set_ylim(-6,10);
fig
plt.show();plt.clf()
# data위치는 바뀜
x = np.arange(1,40)
y = x * 1.1
plt.scatter(x, y, marker='.');
plt.axis('equal')
## (-0.9000000000000001, 40.9, -0.9900000000000002, 44.99000000000001)
plt.annotate('interesting point', xy=(4,5), xytext=(20,10), arrowprops=dict(shrink=0.05))
plt.show();plt.clf()
x1 = np.random.normal(30, 3, 100)
x2 = np.random.normal(20, 3, 100)
x3 = np.random.normal(10, 3, 100)
plt.plot(x1, label = 'p1');
plt.plot(x2, label = 'p2');
plt.plot(x3, label = 'p3');
plt.legend(bbox_to_anchor=(0., 1.02, 1., 0.102), loc=0, ncol=3, mode='extend',
borderaxespad=0.);
plt.annotate("important value", (50,20), xytext=(5,40), arrowprops=dict(arrowstyle='->'));
plt.annotate("incorrect value", (40,30), xytext=(50,40), arrowprops=dict(arrowstyle='->'));
plt.show();plt.clf()
#주석달기
| 문자 | 색상 |
|---|---|
NullLocator |
눈금없음 |
FixedLocator |
눈금위치고정 |
IndexLocator |
인덱스플롯을 위한 위치 지시자 |
LinearLocator |
min에서 max까지 일정간격 눈금 |
MultipleLocator |
min에서 max까지 로그단위 눈금 |
MaxNLocator |
눈금과 범위가 기본값의 배수 |
AutoLocator |
간단한 기본값을 가지는 MaxNlocator |
AutoMinorLocator |
보조눈금에 대한 위치 지시자 |
NullFormatter |
눈금레이블 없음 |
IndexFormatter |
레이블 목록에서 문자열 설정 |
FixedFormatter |
레이블에 직접문자열 설정 |
FuncFormatter |
사용자 정의 함수로 레이블 설정 |
FormatStrFormatter |
각 값에 대한 포맷 문자열 사용 |
ScalarFormatter |
스칼라값에 대한 포맷 지시자 |
LogFormatter |
로그 축에 대한 기본 포맷 지시자 |
plt.axes(xscale='log', yscale='log');
plt.show()
ax = plt.axes()
ax.plot(np.random.randn(100).cumsum());
ax.yaxis.set_major_locator(plt.NullLocator());
ax.xaxis.set_major_formatter(plt.NullFormatter());
plt.show();plt.clf()
# locater 와 formatter를 null값으로
fix, ax = plt.subplots(3, 3, sharex=True, sharey=True);
#y와 x를 share 함
for axi in ax.flat:
axi.xaxis.set_major_locator(plt.MaxNLocator(4));
axi.yaxis.set_major_locator(plt.MaxNLocator(4));
fig
plt.show();plt.clf()
# 각축마다 locator max 4개만 표시되도록
x = np.linspace(-np.pi, np.pi, 1000, endpoint=True)
y = np.sin(x)
plt.plot(x, y);
ax = plt.gca()
ax.spines['bottom'].set_position(('data',0))
ax.spines['left'].set_position(('data',0))
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
plt.show();plt.clf()
# 축의 눈금정보를 가운데에 표시하는것
#축을 기준으로 x는 밑에 y는 왼쪽에
x = np.linspace(1, 10)
y = [10 ** el for el in x]
z = [2 * el for el in x]
fig = plt.figure(figsize=(10, 8))
ax1 = fig.add_subplot(2, 2, 1)
ax1.plot(x,y, '-y');
ax1.set_yscale('log');
ax1.set_title(r'Logarithmic plot of $ {10}^{x} $' );
ax1.set_ylabel(r'${y} = {10}^{x} $');
plt.grid(b=True, which='both', axis='both');
ax2 = fig.add_subplot(2, 2, 2)
ax2.plot(x,y, '--r');
ax2.set_yscale('linear');
ax2.set_title(r'Linear plot of $ {10}^{x} $' );
ax2.set_ylabel(r'${y} = {10}^{x} $');
plt.grid(b=True, which='both', axis='both');
ax3 = fig.add_subplot(2, 2, 3)
ax3.plot(x,y, '-.g');
ax3.set_yscale('log');
ax3.set_title(r'Logarithmic plot of $ {2}^{x} $' );
ax3.set_ylabel(r'${y} = {2}^{x} $');
plt.grid(b=True, which='both', axis='both');
ax4 = fig.add_subplot(2, 2, 4)
ax4.plot(x,y, ':b');
ax4.set_yscale('linear');
ax4.set_title(r'Linear plot of $ {2}^{x} $' );
ax4.set_ylabel(r'${y} = {2}^{x} $');
plt.grid(b=True, which='both', axis='both');
plt.show();plt.clf()
fig = plt.figure(figsize=(10,10));
x = range(1,11);
columns = [np.random.randn(10) * i for i in range(1,26)];
for n, v in enumerate(plt.style.available[1:]):
plt.style.use(v);
plt.subplot(5, 5, n + 1);
plt.title(v);
for c in columns:
plt.plot(x, c, marker='', color='royalblue', linewidth=1, alpha=0.4);
plt.subplots_adjust(hspace=0.5, wspace=0.4);
plt.show();plt.clf()
plt.style.use(['seaborn-notebook'])
| 함수 | 설명 |
|---|---|
bar |
막대 플롯(bar plot) 생성 |
barbs |
barbs의 2차원 필드 그리기 |
boxplot |
상자 및 수염 플롯 생성 |
cohere |
x와 y의 일관성 시각화 그리기 |
contour |
플롯 등고선 |
errorbar |
오류 막대 그래프 |
hexbin |
육각형 binning 플롯 생성 |
hist |
히스토그램 플롯 |
imshow |
축에 이미지 표시 |
pcolor |
2차원 배열의 유사 플롯 생성 |
pcolormesh |
사각 망사 그래프 |
pie |
파이 차트 플롯 |
plot |
플롯 라인 또는 마커 |
quiver |
화살표의 2차원 필드 생성 |
sankey |
Sankey 흐름도 생성 |
scatter |
x대 y의 산점도 생성 |
stem |
줄기 그래프 생성 |
streamplot |
벡터 흐름의 스트림 라인 그리기 |
height = [np.random.randn() * i for i in range(1,6)]
names = ['A', 'B', 'C', 'D', 'E'];
y_pos = np.arange(len(names));
plt.bar(y_pos, height);
plt.xticks(y_pos, names, fontweight='bold');
plt.xlabel('group');
plt.show();plt.clf()
height = [np.random.randn() * i for i in range(1,6)]
names = ['A', 'B', 'C', 'D', 'E']
y_pos = np.arange(len(names));
plt.barh(y_pos, height);
plt.yticks(y_pos, names, fontweight='bold');
plt.ylabel('group');
plt.show();plt.clf()
#horizon
bars1 = [12, 28, 1, 8, 22]
bars2 = [28, 7, 16, 4, 10]
bars3 = [25, 3, 23, 25, 17]
bars = np.add(bars1, bars2).tolist()
#bars 에 합침
r= [0, 1, 2, 3, 4]
names = ['A', 'B', 'C', 'D', 'E']
plt.bar(r, bars1, color='royalblue', edgecolor='white');
plt.bar(r, bars2, bottom=bars1, color='skyblue', edgecolor='white');
plt.bar(r, bars3, bottom=bars2, color='lightblue', edgecolor='white');
plt.xlabel('group', fontweight='bold');
plt.xticks(r, names, fontweight='bold');
plt.show();plt.clf()
bar_width = 0.25
bars1 = [14, 17, 9, 8, 7]
bars2 = [14, 7, 12, 4, 10]
bars3 = [21, 4, 24, 13, 17]
r1 = np.arange(len(bars1))
r2 = [x + bar_width for x in r1]
r3 = [x + bar_width for x in r2]
names = ['A', 'B', 'C', 'D', 'E']
plt.bar(r1, bars1, label='r1', width=bar_width, color='royalblue', edgecolor='white');
plt.bar(r2, bars2, label='r2',width=bar_width, color='skyblue', edgecolor='white');
plt.bar(r3, bars3, label='r3', width=bar_width, color='lightblue', edgecolor='white');
plt.xlabel('group', fontweight='bold');
plt.xticks([r + bar_width for r in range(len(bars1))], names);
plt.legend();
plt.show();plt.clf()
x = [0, 5, 10, 15, 30, 40, 50, 60, 100]
v = [0, -5, -10, -15, -30, -40, -50, -60, -100]
n = len(v)
y = np.ones(n)
u = np.zeros(n)
plt.barbs(x, y, u, v, length=9)
plt.xticks(x)
## ([<matplotlib.axis.XTick object at 0x0000000009DC3C40>, <matplotlib.axis.XTick object at 0x0000000009DC3940>, <matplotlib.axis.XTick object at 0x00000000058DF490>, <matplotlib.axis.XTick object at 0x0000000005845160>, <matplotlib.axis.XTick object at 0x0000000005845EB0>, <matplotlib.axis.XTick object at 0x00000000058492B0>, <matplotlib.axis.XTick object at 0x0000000005849C10>, <matplotlib.axis.XTick object at 0x00000000058450A0>, <matplotlib.axis.XTick object at 0x00000000058518E0>], [Text(0, 0, ''), Text(0, 0, ''), Text(0, 0, ''), Text(0, 0, ''), Text(0, 0, ''), Text(0, 0, ''), Text(0, 0, ''), Text(0, 0, ''), Text(0, 0, '')])
plt.ylim(0.98, 1.05);
plt.show();plt.clf()
x = np.linspace(0.1, 2 * np.pi, 41)
y = np.exp(np.sin(x))
plt.stem(x, y, linefmt='gray', bottom=1, use_line_collection=True);
plt.show();plt.clf()
r1 = np.random.normal(loc=0, scale=0.5, size=100);
r2 = np.random.normal(loc=0.5, scale=1, size=100);
r3 = np.random.normal(loc=1, scale=1.5, size=100);
r4 = np.random.normal(loc=1.5, scale=2, size=100);
r5 = np.random.normal(loc=2, scale=2.5, size=100);
f, ax = plt.subplots(1,1);
ax.boxplot((r1, r2, r3, r4, r5), patch_artist=True);
ax.set_xticklabels(['r1', 'r2', 'r3', 'r3', 'r5']);
plt.show();plt.clf()
| 문자 | marker |
|---|---|
. |
point |
, |
pixel |
o |
circle |
v |
triangle_down |
^ |
triangle_up |
< |
triangle_left |
> |
triangle_right |
1 |
tri_down |
2 |
tri_up |
3 |
tri_left |
4 |
tri_right |
s |
square |
p |
pentagon |
* |
star |
h |
hexagon1 |
H |
hexagon2 |
+ |
plus |
D |
diamond |
d |
thin_diamond |
| |
vline |
_ |
hline |
plt.figure(figsize=(8, 4))
markers = ['-', ',', 'o', 'v', '^', '<', '>', '1', '2', '3', '4','s','p', '*', 'h','H','+','D','d','|', '_']
for m in markers:
plt.plot(np.random.rand(5), np.random.rand(5), m, label="'{0}'".format(m));
plt.legend(loc='center right', ncol=2);
plt.xlim(0, 1.5);
plt.show();plt.clf()
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y, 'o');
plt.show();plt.clf()
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.scatter(x, y, marker='o');
plt.show();plt.clf()
#scatter은 marker를 붙여줘야함
for i in range(9):
y = np.random.randn(1000).cumsum()
x = np.arange(1000)
plt.scatter(x, y, alpha=0.2, cmap='viridis');
plt.show();plt.clf()
x= np.random.randn(100)
y= np.random.randn(100)
colors = np.random.rand(100)
sizes = 1000 * np.random.rand(100)
plt.scatter(x, y, c=colors, s=sizes, alpha=0.3, cmap='viridis');
plt.colorbar();
plt.show();plt.clf()
x= np.random.randn(100)
y= np.random.randn(100)
colors = np.random.rand(100)
sizes = 1000 * np.random.rand(100)
plt.scatter(x, y, c=colors, s=sizes, alpha=0.3, cmap='inferno');
plt.colorbar();
plt.show();plt.clf()
x = np.random.randn(200)
y1 = np.random.randn(len(x))
y2 = 1.1 * np.exp(x)
ax1 = plt.plot();
plt.scatter(x, y1, c='indigo', alpha=0.3, label='no correlation');
plt.scatter(x, y2, c='blue', alpha=0.3, label='correlation');
plt.grid(True);
plt.legend();
plt.show();plt.clf()
dt = 0.01
t = np.arange(0, 30, dt)
n1 = np.random.randn(len(t))
n2 = np.random.randn(len(t))
s1 = 1.5 * np.sin(2 * np.pi * 10 * t) + n1
s2 = np.cos(np.pi * t) + n2
plt.cohere(s1, s2 ** 2, 128, 1./dt );
plt.xlabel('time');
plt.ylabel('coherence');
plt.show();plt.clf()
plt.subplots_adjust(wspace=1)
dt = 0.01
t = np.arange(0, 30, dt)
n1 = np.random.randn(len(t))
n2 = np.random.randn(len(t))
r = np.exp(-t/0.05)
c1 = np.convolve(n1, r, mode='same') *dt
c2 = np.convolve(n2, r, mode='same') *dt
s1 = 0.01 * np.sin(2 * np.pi * 10 * t) +c1
s2 = 0.01 * np.sin(2 * np.pi * 10 * t) +c2
plt.subplot(211);
plt.plot(t, s1, t, s2);
plt.xlim(0, 5);
plt.xlabel('time');
plt.ylabel('s1 & s2');
plt.grid(True)
plt.subplot(212);
plt.cohere(s1, s2, 256, 1./dt);
plt.ylabel('coherence');
plt.show();plt.clf()
s1 = 1.5 * np.sin(2 * np.pi * 10 * t) +c1
s2 = np.cos(np.pi * t) + c2 + np.sin(2 * np.pi * 10 * t)
fig, [ax1, ax2] = plt.subplots(2,1);
ax1.plot(t, s1, t, s2);
ax1.set_xlim(0, 5);
ax1.set_xlabel('time');
ax1.set_ylabel('s1 & s2');
ax1.grid(True);
ax2.cohere(s1, s2, 256, 1./dt);
ax2.set_ylabel('coherence');
plt.show();plt.clf()
d1 = np.random.randn(365).cumsum()
t1 = sum(d1)
av1 = t1 / len(d1)
z1 = [i - av1 for i in d1]
d2 = np.random.randn(365).cumsum()
t2 = sum(d2)
av2 = t2 / len(d2)
z2 = [i - av1 for i in d2]
fig = plt.figure()
ax1 = fig.add_subplot(311)
ax1.plot(d1);
ax2 = fig.add_subplot(312)
ax2.plot(d2);
ax3 = fig.add_subplot(313)
ax3.xcorr(z1, z2, usevlines=True, maxlags=None, normed=True, lw=2);
plt.ylim(-1, 1);
plt.show();plt.clf()
#어디서 차이가 나는지 corr 계산
x = np.linspace(0, 20, 40)
dy = 1
y = np.sin(x) + dy * np.random.randn(40)
plt.errorbar(x, y, yerr=dy, fmt='H');
plt.show();plt.clf()
plt.errorbar(x, y, yerr=dy, fmt='s', c='darkblue',ecolor='gray', elinewidth=2,
capsize=0);
plt.show();plt.clf()
plt.pcolor(np.random.rand(20,20), cmap='Reds');
plt.show();plt.clf()
plt.pcolor(np.random.rand(20,20), cmap='Blues');
plt.show();plt.clf()
data = np.random.randn(1000)
plt.hist(data);
plt.show();plt.clf()
plt.hist(data, bins=50, alpha=0.5, histtype='stepfilled', color='steelblue', edgecolor='none');
plt.show();plt.clf()
x1 = np.random.normal(0, 1, 10000)
x2 = np.random.normal(-5, 3, 10000)
x3 = np.random.normal(5, 2, 10000)
d = dict(histtype='stepfilled', alpha=0.3, bins=50 )
plt.hist(x1, **d);
plt.hist(x2, **d);
plt.hist(x3, **d);
plt.show();plt.clf()
x = np.random.normal(size=50000)
y = x - np.random.normal(size=50000)
#size안주고 숫자넣으면 에러남
plt.hist2d(x, y, bins=50, cmap='OrRd');
plt.colorbar();
plt.show();plt.clf()
plt.hexbin(x, y, gridsize=50, cmap='OrRd');
plt.colorbar();
plt.show();plt.clf()
a = np.arange(-1, 1, 0.1)
X, Y = np.meshgrid(a, a)
Z = np.sin(X * Y)
CS = plt.contour(X, Y, Z, levels=a)
plt.clabel(CS, inline=2);
plt.colorbar();
plt.show();plt.clf()
def f(x, y):
return (1 - (x ** 2 + y**2)) * np.exp(-y ** 2/2)
x = np.arange(-1.5, 1.5, 0.1)
y = np.arange(-1.5, 1.5, 0.1)
X, Y = np.meshgrid(x, y)
Z = f(X, Y)
N = np.arange(-1, 2, 0.2)
CS = plt.contour(Z, N, linewidths=2, cmap='rainbow')
plt.clabel(CS, inline=True, fmt='%1.1f');
plt.colorbar(CS);
plt.show();plt.clf()
l = np.linspace(-1.0, 1.0, 1000)
X, Y = np.meshgrid(l,l)
Z = np.sqrt(X ** 2 + Y ** 2)
lv = np.linspace(Z.reshape(-1, 1).min(), Z.reshape(-1, 1).max(), 40)
plt.contour(X, Y, Z, levels=lv)
## <matplotlib.contour.QuadContourSet object at 0x000000006AAFA490>
plt.colorbar();
plt.show();plt.clf()
plt.contourf(X, Y, Z, levels=lv)
## <matplotlib.contour.QuadContourSet object at 0x000000006B65CF10>
plt.colorbar();
plt.show();plt.clf()
plt.imshow(Z, extent=[-1, 1, -1, 1], origin='lower', cmap='rainbow', alpha=0.4);
plt.show();plt.clf()
# 경계없이 표현 가능
Y, X = np.mgrid[0:5:100j, 0:5:100j]
U = X
V = np.sin(Y)
plt.streamplot(X, Y, U, V);
plt.show();plt.clf()
Y, X = np.mgrid[-3:3:100j, -3:3:100j]
U = -1 - X ** 2 + Y
V = 1 + X - Y ** 2
speed = np.sqrt(U ** 2 + V ** 2)
plt.figure(figsize=(12,7));
plt.streamplot(X, Y, U, V, density=1);
plt.show();plt.clf()
import sympy
x, y = sympy.symbols('x y')
f = x**2 + y**2 + x*y - sympy.sin(x) * 4
fdx = sympy.diff(f, x)
fdy = sympy.diff(f, y)
sample_size = 100
xs, ys = np.meshgrid(np.linspace(-10, 10, sample_size), np.linspace(-10, 10, sample_size))
zs = [float(f.subs(x, xv).subs(y, yv)) for xv, yv in zip(xs.ravel(), ys.ravel())]
zs = np.array(zs).reshape(sample_size, sample_size)
plt.contour(xs, ys, zs, 40, levels=np.logspace(-0.5, 2.0, 40), cmap='rainbow')
## <matplotlib.contour.QuadContourSet object at 0x0000000005A4FAC0>
xs_q, ys_q = np.meshgrid(np.linspace(-10, 10, 10), np.linspace(-10, 10, 10))
xsg = [-float(fdx.subs(x, xv).subs(y, yv)) for xv, yv in zip(xs_q.ravel(), ys_q.ravel())];
ysg = [-float(fdx.subs(x, xv).subs(y, yv)) for xv, yv in zip(xs_q.ravel(), ys_q.ravel())];
plt.quiver(xs_q, ys_q, xsg, ysg, width=0.005, scale=500, color='black');
plt.show();plt.clf()
data = [10, 50, 30, 40, 60]
categories = ['C1', 'C2', 'C3', 'C4', 'C5']
plt.pie(data, labels=categories, autopct='%0.1f%%')
## ([<matplotlib.patches.Wedge object at 0x000000006A02F790>, <matplotlib.patches.Wedge object at 0x000000006C6E5640>, <matplotlib.patches.Wedge object at 0x000000006C6E5D60>, <matplotlib.patches.Wedge object at 0x000000006C6F54C0>, <matplotlib.patches.Wedge object at 0x000000006C6F5BE0>], [Text(1.0849974335199486, 0.1810540506454493, 'C1'), Text(0.4418649348526167, 1.0073506734735889, 'C2'), Text(-0.8680545886354037, 0.6756339475996008, 'C3'), Text(-0.9674211121378465, -0.5235421585602944, 'C4'), Text(0.6016429671278825, -0.9208831305358774, 'C5')], [Text(0.5918167819199719, 0.09875675489751778, '5.3%'), Text(0.24101723719233634, 0.5494640037128666, '26.3%'), Text(-0.4734843210738565, 0.3685276077816004, '15.8%'), Text(-0.5276842429842798, -0.2855684501237969, '21.1%'), Text(0.3281688911606631, -0.5022998893832058, '31.6%')])
plt.legend(categories);
plt.show();plt.clf()
explode = [0.1, 0.1, 0.1, 0.1, 0.1]
plt.pie(data, explode=explode, labels=categories, autopct='%0.1f%%')
## ([<matplotlib.patches.Wedge object at 0x0000000007C85E20>, <matplotlib.patches.Wedge object at 0x0000000007C925E0>, <matplotlib.patches.Wedge object at 0x0000000007C92D00>, <matplotlib.patches.Wedge object at 0x0000000007C9E460>, <matplotlib.patches.Wedge object at 0x0000000007C9EB80>], [Text(1.183633563839944, 0.1975135097950356, 'C1'), Text(0.48203447438467273, 1.0989280074257333, 'C2'), Text(-0.9469686421477131, 0.7370552155632009, 'C3'), Text(-1.05536848596856, -0.5711369002475939, 'C4'), Text(0.6563377823213263, -1.0045997787664118, 'C5')], [Text(0.6904529122399672, 0.11521621404710408, '5.3%'), Text(0.2811867767243924, 0.641041337665011, '26.3%'), Text(-0.5523983745861659, 0.42994887574520047, '15.8%'), Text(-0.6156316168149931, -0.3331631918110964, '21.1%'), Text(0.382863706354107, -0.5860165376137401, '31.6%')])
plt.legend(categories);
plt.show();plt.clf()
#간격 주는것
df = pd.DataFrame({
'group' : ['A','B', 'C', 'D'],
'var1' : [38, 1.5, 30, 4],
'var2' : [29, 10, 9, 34],
'var3' : [8, 39, 23, 24],
'var4' : [7, 31, 33, 14],
'var5' : [28, 15, 32, 14]})
categories = list(df)[1:]
N = len(categories)
angles = [n / float(N) * 2 * np.pi for n in range(N)]
angles += angles[:1]
ax = plt.subplot(111, polar=True)
ax.set_theta_offset(np.pi /2 ) #원형으로 표현
ax.set_theta_direction(-1)
ax.set_rlabel_position(0)
plt.xticks(angles[:-1], categories);
plt.yticks([10, 20, 30], ["10", "20", "30"], color ='gray', size=7);
plt.ylim(0, 40);
values = df.loc[0].drop('group').values.flatten().tolist()
values += values[:1]
ax.plot(angles, values, linewidth=1, linestyle='solid', label='A');
ax.fill(angles, values, 'b', alpha=0.1);
values = df.loc[1].drop('group').values.flatten().tolist()
values += values[:1]
ax.plot(angles, values, linewidth=1, linestyle='solid', label='B');
ax.fill(angles, values, 'r', alpha=0.1);
plt.legend(bbox_to_anchor=(0.1, 0.1));
plt.show();plt.clf()
from matplotlib.sankey import Sankey
Sankey(flows=[0.20, 0.15, 0.25, -0.25, -0.25, -0.15, -0.60, -0.20],
labels=['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven'],
orientations=[-1, -1, 0, 1, 1, 1, 0, -1]).finish();
plt.show();plt.clf()
from mpl_toolkits import mplot3d
fig = plt.figure()
## <string>:1: RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam `figure.max_open_warning`).
ax = plt.axes(projection='3d')
plt.show();plt.clf()
x = range(1, 101)
y = np.random.randn(100) * x
z = np.random.randn(100) * x
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d');
ax.scatter(x, y, z, c='green', s=60);
plt.show();plt.clf()
ax = plt.axes(projection='3d')
zline = np.linspace(0, 20, 1000)
xline = np.sin(zline)
yline = np.cos(zline)
ax.plot3D(xline, yline, zline, 'gray')
zdata = 20 * np.random.random(100)
xdata = np.sin(zdata) + 0.2 * np.random.randn(100)
ydata = np.cos(zdata) + 0.2 * np.random.randn(100)
ax.scatter3D(xdata, ydata, zdata, c=zdata, cmap='Blues')
plt.show();plt.clf()
def f(x, y):
return np.cos(np.sqrt(x **2 + y **2))
l = np.linspace(-4, 4, 20)
X, Y = np.meshgrid(l, l)
Z = f(X, Y)
fig = plt.figure()
ax = plt.axes(projection='3d')
ax.contour3D(X, Y, Z, 50, cmap='BuPu')
## <matplotlib.contour.QuadContourSet object at 0x0000000009B595E0>
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
plt.show();
ax.view_init(60,30)
fig
plt.show();plt.clf()
fig = plt.figure()
ax = plt.axes(projection='3d')
ax.plot_wireframe(X, Y, Z, color='gray')
plt.show();plt.clf
## <function clf at 0x000000005FE770D0>
ax = plt.axes(projection='3d')
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='viridis', edgecolor='none')
plt.show();plt.clf()
r = np.linspace(0, 6, 20)
theta = np.linspace(-0.8 * np.pi, 0.8 * np.pi, 40)
r, theta = np.meshgrid(r, theta)
X = r * np.sin(theta)
Y = r * np.cos(theta)
Z = f(X, Y)
ax = plt.axes(projection='3d')
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='viridis', edgecolor='none')
plt.show();plt.clf()
theta = 2 * np.pi * np.random.random(1000)
r = 6 * np.random.random(1000)
X = np.ravel(r * np.sin(theta))
Y = np.ravel(r * np.cos(theta))
Z = f(X, Y)
ax = plt.axes(projection='3d')
ax.scatter(X, Y, Z, c=Z, cmap='viridis', linewidth=0.5);
plt.show();plt.clf()
ax = plt.axes(projection='3d')
ax.plot_trisurf(X, Y, Z, cmap='viridis', edgecolor='None')
plt.show();plt.clf()
x = np.random.normal(5, 1, 100)
y = np.random.normal(3, 0.5, 100)
fig = plt.figure(figsize=(8, 10))
hist, xedges, yedges = np.histogram2d(x, y, bins=10)
elements = (len(xedges) -1 ) * (len(yedges) -1)
xpos, ypos = np.meshgrid(xedges[:-1]+0.25, yedges[:-1]+0.25)
xpos = xpos.flatten()
ypos = ypos.flatten()
zpos = np.zeros(elements)
dx = 0.1 * np.ones_like(zpos)
dy = dx.copy()
dz = hist.flatten()
ax = fig.add_subplot(211);
ax.scatter(x, y, alpha=0.5);
ax.set_xlabel('X Axis')
ax.set_ylabel('Y Axis')
ax2 = fig.add_subplot(212, projection='3d');
ax2.bar3d(xpos, ypos, zpos, dx, dy, dz, alpha =0.4);
ax2.set_xlabel('X Axis');
ax2.set_ylabel('Y Axis');
ax2.set_zlabel('Z Axis');
plt.show();plt.clf()